package com.elitect.ftptransfer.util;

import java.io.File;
import java.util.Stack;

public final class Utils
{
    private Utils()
    {
    }

    public static String getSizeString(long size)
    {
        String byteString = " B";
        String kilobyteString = " KB";
        String megabyteString = " MB";
        String gigabyteString = " GB";
        int unit = 1024;

        double kilobyte, megabyte, gigabyte;
        kilobyte = 1.0 * size / unit;
        if (kilobyte < 1)
        {
            return (size % unit) + byteString;
        }
        megabyte = kilobyte / unit;
        kilobyte = round(kilobyte, 1);
        if (megabyte < 1)
        {
            return kilobyte + kilobyteString;
        }
        gigabyte = megabyte / unit;
        megabyte = round(megabyte, 1);
        if (gigabyte < 1)
        {
            return megabyte + megabyteString;
        }

        gigabyte = round(gigabyte, 1);
        return gigabyte + gigabyteString;
    }

    /**
     * Get round with decimal part
     * 
     * @param number
     * @param digit
     * @return
     */
    public static double round(double number, int digit)
    {
        if (digit > 0)
        {
            int temp = 1;
            for (int i = 1; i <= digit; i++)
            {
                temp *= 10;
            }
            number = number * temp;
            number = Math.round(number);
            number = number / temp;
            return number;
        }
        else
        {
            return 0;
        }
    }

    /**
     * Get the size of local files. It needs to calculate on a thread.
     * 
     * @param file
     * @return size of a file or directory
     */
    public static long sizeOf(File file)
    {
        if (file == null)
        {
            return 0;
        }

        long size = 0;
        Stack<File> stack = new Stack<File>();
        stack.push(file);
        while (!stack.empty())
        {
            File popFile = stack.pop();
            if (popFile.isFile())
            {
                size += popFile.length();
            }
            else
            {
                File[] files = file.listFiles();
                for (File file2 : files)
                {
                    stack.push(file2);
                }
            }
        }

        return size;
    }
}
